package cn.dw.web.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.dw.domain.CheckInfo;
import cn.dw.domain.People;
import cn.dw.domain.Point;
import cn.dw.service.CheckInfoService;
import cn.dw.service.PeopleService;
import cn.dw.service.PointService;
import cn.dw.service.WeChatService;
import cn.dw.utils.BaiduMapUtil;
import net.sf.json.JSONObject;

public class PeopleAction extends ActionSupport implements ModelDriven<People> {
	private static final long serialVersionUID = -5377627246094963357L;
	private People people = new People();
	private PeopleService ps;
	private PointService pts;
	private CheckInfoService cis;
	private WeChatService wcs;
	private ChangetoJson ctj = new ChangetoJson();
	private String result;

	public String list() throws Exception {
		Map<String, Object> map = null;

		List<People> peoples = this.ps.getAll();

		List<Map<String, Object>> list = new ArrayList<>();

		People peo = new People();
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				peo = (People) peoples.get(i);

				map = new HashMap<>();

				String numb = peo.getNumb().toString();
				for (int a = 0; a < 4 - peo.getNumb().toString().length(); a++) {
					numb = "0" + numb;
				}
				if ((peo.getIfleader().intValue() == 1)
						|| (peo.getIfleader().intValue() == 2)) {
					map.put("id", peo.getNumb());
					map.put("UnitName", peo.getPoint().getName());
					map.put("Address", peo.getPoint().getAddr());
					map.put("Contacts", peo.getName());
					map.put("Mobile", peo.getPhone());

					String point2 = BaiduMapUtil.point_location(peo.getPoint()
							.getLng(), peo.getPoint().getLat());

					map.put("Point", point2);
					map.put("lng", peo.getPoint().getLng());
					map.put("lat", peo.getPoint().getLat());
					if (peo.getIfleader().intValue() == 1) {
						map.put("status", Integer.valueOf(0));
					}
					if (peo.getIfleader().intValue() == 2) {
						map.put("status", Integer.valueOf(1));
					}
					map.put("dele", Integer.valueOf(0));
					list.add(map);
				}
			}
		}
		this.ctj.json(list);
		return null;
	}

	public String check() throws Exception {
		List<People> peoples = this.ps.getAll();

		Map<String, Object> map = null;

		List<Map<String, Object>> list = new ArrayList<>();

		People peo = new People();
		Point point = new Point();
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				peo = (People) peoples.get(i);
				point = peo.getPoint();
				if (peo.getLevel().intValue() == 1) {
					map = new HashMap<>();

					map.put("people", peo.getName());
					map.put("addr", point.getName());
					map.put("phone", peo.getPhone());
					map.put("ID", point.getId());
					list.add(map);
				}
			}
		}
		this.ctj.json(list);

		return null;
	}

	public String login() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");

		String username = request.getParameter("username");

		String password = request.getParameter("password");

		Map<String, Object> map = new HashMap<>();
		map.put("username", username);
		map.put("password", password);

		this.people.setUsername(username);
		this.people.setPassword(password);
		try {
			People p = this.ps.login(this.people);
			if (p.getLevel().intValue() == 0) {
				ActionContext.getContext().getSession().put("user", p);
				ActionContext.getContext().getSession()
						.put("username", username);

				map.put("msg", Integer.valueOf(1));
				JSONObject json = JSONObject.fromObject(map);
				this.result = json.toString();
				return "toHome";
			}
			addActionError("权限不足");
			map.put("msg", Integer.valueOf(0));
			JSONObject json = JSONObject.fromObject(map);
			this.result = json.toString();
			return "login";
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", Integer.valueOf(2));
			JSONObject json = JSONObject.fromObject(map);
			this.result = json.toString();
			addActionError(e.getMessage());
		}
		return "login";
	}

	public String index() throws Exception {
		String object = (String) ActionContext.getContext().getSession().get("username");

		Map<String, Object> map = new HashMap<>();

		map.put("msg", object);

		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();
		return "index";
	}

	@SuppressWarnings("rawtypes")
	public String quit() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();

		Enumeration em = request.getSession().getAttributeNames();
		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		Map<String, Object> map = new HashMap<>();

		map.put("msg", Integer.valueOf(1));

		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "quit";
	}

	public String review() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String num = request.getParameter("id");
		Map<String, Object> map = new HashMap<>();
		Integer id = new Integer(num);
		People peo = this.ps.getById(id);
		peo.setLevel(Integer.valueOf(1));
		peo.setIfleader(Integer.valueOf(2));
		this.ps.update(peo);
		map.put("msg", "已将 " + peo.getName() + " 审核通过为组长！");
		JSONObject json = JSONObject.fromObject(map);
		this.result = json.toString();
		return "review";
	}

	public String del() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String num = request.getParameter("id");
		Map<String, Object> map = new HashMap<>();
		Integer id = new Integer(num);
		People peo = this.ps.getById(id);
		peo.setLevel(Integer.valueOf(2));
		peo.setIfleader(Integer.valueOf(0));
		this.ps.update(peo);
		map.put("msg", "已将 " + peo.getName() + " 从审核页面删除！");
		JSONObject json = JSONObject.fromObject(map);
		this.result = json.toString();
		return "del";
	}

	public String allcheck() throws Exception {
		List<People> peoples = this.ps.getAll();

		Map<String, Object> map = new HashMap<>();

		List<Map<String, Object>> list = new ArrayList<>();
		Integer count = Integer.valueOf(0);
		People peo = new People();
		Point point = new Point();
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				peo = (People) peoples.get(i);
				if (peo.getLevel().intValue() == 1) {
					point = peo.getPoint();

					count = send_check(point);
				}
			}
		}
		if (count.intValue() != 0) {
			map.put("msg", Integer.valueOf(1));

			list.add(map);
		}
		JSONObject json = JSONObject.fromObject(map);
		this.result = json.toString();

		return "allcheck";
	}

	public String random() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");

		String random = request.getParameter("randomvalue");

		List<People> peoples = this.ps.getAll();

		List<People> peoples2 = new ArrayList<>();

		People peo = new People();
		Point point = new Point();

		Integer randomValue = new Integer(random);
		Map<String, Object> map = new HashMap<>();
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				peo = new People();
				peo = (People) peoples.get(i);
				if (peo.getLevel().intValue() == 1) {
					peoples2.add(peo);
				}
			}
		}
		if (randomValue.intValue() <= peoples2.size()) {
			int[] a = new int[randomValue.intValue()];
			Random random2 = new Random();
			int count = 0;
			while (count < a.length) {
				boolean flag = true;
				int r = random2.nextInt(peoples2.size() + 1);
				for (int i = 0; i < a.length; i++) {
					if (r == a[i]) {
						flag = false;
						break;
					}
				}
				if (flag) {
					a[count] = r;
					count++;
				}
			}
			Integer iii = Integer.valueOf(0);
			for (int i = 0; i < a.length; i++) {
				peo = (People) peoples2.get(a[i] - 1);

				point = peo.getPoint();

				iii = send_check(point);
			}
			if (iii.intValue() > 0) {
				map.put("msg", Integer.valueOf(1));
			}
		} else if (randomValue.intValue() > peoples2.size()) {
			map.put("msg", Integer.valueOf(2));
		}
		JSONObject json = JSONObject.fromObject(map);
		this.result = json.toString();

		return "random";
	}

	public String listcheck() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();

		request.setCharacterEncoding("utf-8");

		Map<String, Object> map = new HashMap<>();

		String[] list = request.getParameterValues("steps");

		Integer iii = Integer.valueOf(0);
		for (int i = 0; i < list.length; i++) {
			Integer point_id = new Integer(list[i]);

			iii = send_check(this.pts.getById(point_id));
		}
		if (iii.intValue() > 0) {
			map.put("msg", Integer.valueOf(1));
		}
		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "listcheck";
	}

	public Integer send_check(Point point) throws Exception {
		Integer count = Integer.valueOf(0);

		List<Map<String, Object>> opidList = this.ps.check(point.getId());

		CheckInfo cInfo = new CheckInfo();

		List<People> peoples = this.ps.getByPointId(point.getId());
		for (int i = 0; i < peoples.size(); i++) {
			if (((People) peoples.get(i)).getLevel().intValue() == 1) {
				cInfo.setPeople((People) peoples.get(i));
			}
		}
		cInfo.setDate(new Date());

		cInfo.setReply(false);

		this.cis.save(cInfo);
		if (opidList.size() > 0) {
			for (int j = 0; j < opidList.size(); j++) {
				String openid = ( opidList.get(j)).get("openid").toString();

				String peoplename = ( opidList.get(j)).get("peoplename")
						.toString();
				String checkInfoId = ((CheckInfo) this.cis.getAll().get(
						this.cis.getAll().size() - 1)).getCheckid().toString();
				this.wcs.send_template_message(openid, peoplename, checkInfoId);
				System.out.println("查岗中。。。。");
				count = Integer.valueOf(count.intValue() + 1);
			}
		}
		return count;
	}

	public String people_set() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Integer numb = new Integer(request.getParameter("numb"));
		Integer state = new Integer(request.getParameter("state"));
		Integer mynumb = new Integer(request.getParameter("mynumb"));

		Map<String, Object> map = new HashMap<>();

		People peo = new People();

		People peo2 = new People();

		peo2 = this.ps.getById(mynumb);

		peo = this.ps.getById(numb);
		if (peo2.getLevel().intValue() == 1) {
			if (state.intValue() == 1) {
				peo.setIfleader(Integer.valueOf(0));
				peo.setPoint(null);

				this.ps.update(peo);

				map.put("msg", Boolean.valueOf(true));
			} else if (state.intValue() == 0) {
				peo.setIfleader(Integer.valueOf(4));

				this.ps.update(peo);

				map.put("msg", Integer.valueOf(1));
			} else {
				map.put("msg", Integer.valueOf(2));
			}
		} else {
			map.put("msg", Integer.valueOf(3));
		}
		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "people_set";
	}

	public String join() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");

		Map<String, Object> map = new HashMap<>();

		Integer numb = new Integer(request.getParameter("numb"));
		Integer pointid = new Integer(request.getParameter("pointid"));

		People peo = this.ps.getById(numb);
		Point point = this.pts.getById(pointid);
		if (peo != null) {
			peo.setIfleader(Integer.valueOf(3));
			peo.setPoint(point);
			this.ps.update(peo);

			map.put("msg", Integer.valueOf(1));
		} else {
			map.put("msg", Integer.valueOf(2));
		}
		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "join";
	}

	public String nowin() throws Exception {
		List<People> peoples = this.ps.getAll();

		List<Map<String, Object>> list = new ArrayList<>();
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				People people = (People) peoples.get(i);
				Point point = people.getPoint();
				if (people.getIfin().intValue() == 1) {
					Map<String, Object> map = new HashMap<>();

					map.put("numb", people.getNumb());
					map.put("name", people.getName());
					map.put("phone", people.getPhone());
					map.put("addr", point.getName());

					list.add(map);
				}
			}
		}
		this.ctj.json(list);

		return null;
	}

	public String test() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		try {
			String username = request.getParameter("username");

			String password = request.getParameter("password");

			Map<String, Object> map = new HashMap<>();
			map.put("username", username);
			map.put("password", password);

			JSONObject json = JSONObject.fromObject(map);
			this.result = json.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "test";
	}

	public String getResult() {
		return this.result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setPs(PeopleService ps) {
		this.ps = ps;
	}

	public void setPts(PointService pts) {
		this.pts = pts;
	}

	public void setWcs(WeChatService wcs) {
		this.wcs = wcs;
	}

	public void setCis(CheckInfoService cis) {
		this.cis = cis;
	}

	public People getModel() {
		return this.people;
	}
}
